<!-- 账号密码登录 -->
<template>
  <view class="account_login">
    <view class="top">
      <view class="title">登录</view>
    </view>
    <view class="loginForm">
      <uni-forms border :model="form" class="form" ref="loginForm" :rules="rules" err-show-type="toast">
        <uni-forms-item label="" name="nickName">
          <input type="nickname" class="weui-input" v-model="form.nickName" @change="bindblur" placeholder="请输入昵称" />
        </uni-forms-item>
        <uni-forms-item label="头像" name="avatar" label-position="right">
          <view class="rights">
            <button class="cen_item_btn" type="default" open-type="chooseAvatar" @chooseavatar="chooseavatar">
              <image v-if="form.avatar === ''" src="@/static/tx.png" mode=""></image>
              <image v-else :src="form.avatar" mode=""></image>
            </button>
          </view>
        </uni-forms-item>
        <uni-forms-item label="" name="phoneNumber">
          <input class="weui-input" v-model="form.phoneNumber" focus trim maxlength="11" placeholder="请输入手机号" />
        </uni-forms-item>
        <uni-forms-item label="" class="code_input" name="smsCode">
          <view class="bao">
            <input type="number" class="weui-input" v-model="form.smsCode" maxlength="6" placeholder="请输入验证码" />
            <view class="smsCode">
              <view class="flex items-center codeCountdown" v-if="codeEnabled">
                <uni-countdown :showDay="false" :showHour="false" :showMinute="false" :second="30" />
                <text>秒后重新获取</text>
              </view>
              <view class="codeButton" @click="obtainCodeHandle" v-else>获取验证码</view>
            </view>
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>
    <view class="action_btn flex justify-center items-center flex-col">
      <button class="login_btn" @click="login">登录</button>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref, computed } from "vue";
import { getPhoneCode, getOpenId } from "@/api/login";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useUserStore } from "@/store/user.js";
import { guid } from "@/utils/cryptoEncrypt";
const loginForm = ref();
const uuid = guid();
const codeEnabled = ref(false);
const form = reactive({
  phoneNumber: "",
  smsCode: "",
  openId: "",
  nickName: "",
  avatar: "",
});
const shareData = computed(() => {
  // 分享的数据
  return {
    title: "登录",
    path: "pages/login/register",
  };
});
onLoad(() => {
  uni.$mpShare = shareData.value;
  uni.login({
    provider: "weixin",
    success: async function (loginRes) {
      if (!loginRes.code) {
        console.log("获取登录凭证失败");
        return;
      }
      if (loginRes.errMsg === "login:ok") {
        const { code, data, msg } = await getOpenId(loginRes.code);
        if (code == 200) {
          console.log("data", data);
          form.openId = data.openId;
        }
      }
    },
  });
});
onShow(() => {
  uni.$mpShare = shareData.value;
});
const rules = {
  phoneNumber: {
    rules: [
      {
        required: true,
        errorMessage: "请输入手机号",
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        errorMessage: "请输入正确的手机号",
      },
    ],
  },
  smsCode: {
    rules: [
      { required: true, errorMessage: "请输入验证码" },
      {
        pattern: /^\d{4}$/,
        errorMessage: "验证码最多4位",
      },
    ],
  },
};
function bindblur(e) {
  form.nickName = e.target.value;
}
function chooseavatar(e) {
  const { avatarUrl } = e.detail;
  wx.getFileSystemManager().readFile({
    filePath: avatarUrl, //选择图片返回的相对路径
    encoding: "base64", //编码格式
    success: (res) => {
      form.avatar = `data:image/jpeg;base64,${res.data}`;
    },
  });
}
// 注册
const login = () => {
  const user = useUserStore();
  loginForm.value
    .validate()
    .then(async () => {
      form.uuid = uuid;
      console.log("校验通过：", form);
      user.wxRegister(form);
    })
    .catch((err) => {
      console.log("表单错误信息：", err);
    });
};
// 获取验证码
const obtainCodeHandle = () => {
  loginForm.value
    .validateField(["phoneNumber"])
    .then(async (res) => {
      console.log("手机号校验通过：", res);
      codeEnabled.value = true;
      setTimeout(() => {
        codeEnabled.value = false;
      }, 30000);
      const { code } = await getPhoneCode({
        phoneNumber: form.phoneNumber,
        uuid,
      });
      console.log("code", code);
      if (code === 200) {
        uni.showToast({
          title: "验证码发送成功",
          icon: "none",
        });
      }
    })
    .catch((err) => {
      console.log("表单错误信息：", err);
    });
};
</script>
<style scoped lang="scss">
.account_login {
  padding: 80rpx 40rpx;

  .top {
    display: flex;
    flex-direction: column;
    gap: 20rpx;

    .title {
      font-size: 48rpx;
      color: #333;
    }

    .subTitle {
      font-size: 24rpx;
      color: #999;
    }
  }

  .loginForm {
    margin-top: 80rpx;

    :deep(.uni-forms) {
      form {
        .uni-forms-item {
          &:last-child {
            border-bottom: 1px solid #eee;
          }
        }

        .codeCountdown {
          color: #666;
        }
      }
    }

    .codeButton {
      color: #3478f6;
      font-size: 26rpx;
    }
  }

  .bao {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .rights {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-end;
    align-items: flex-end;

    .cen_item_btn {
      width: 80upx;
      height: 80upx;
      margin: 0 !important;
      padding: 0 !important;
      border-radius: 80upx;
      border-color: #fff;

      image {
        width: 80upx;
        height: 80upx;
        border-radius: 80upx;
      }
    }
  }

  .action_btn {
    gap: 20rpx;
    margin-top: 180rpx;

    .login_btn {
      background: #3478f6;
      color: #fff;
      font-size: 28rpx;
      width: 90%;
      height: 90rpx;
      line-height: 90rpx;
    }

    .wx_login {
      font-size: 26rpx;
      color: #5c5c5c;
    }
  }

  .protocol {
    position: absolute;
    bottom: 60rpx;
    left: 0;
    width: 100%;
    font-size: 24rpx;
    text-align: center;
    color: #999;

    .highlightedText {
      color: #3478f6;
    }
  }
}
</style>
